package com.rykj.qxj.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import com.rykj.qxj.server.common.utils.CollectionUtils;



public class Page{
	private static Logger logger = LoggerFactory.getLogger(Page.class);
	  public static final int PAGE_SIZE = 10;
	  private static final String  DOUBLE_REGEXP = "\"";  //替换sql语句中的双引号表达式
	 //一页显示的记录数
	  private int pageSize; 
	 //记录总数
	  private int totalRows; 
	 //总页数
	  private int totalPages; 
	 //当前页码
	  private int currentPage; 
	  //起始行数
	  private int startIndex;
	  //结束行数
	  private int lastIndex;
	  //结果集存放List
	  private List result;
	  private NamedParameterJdbcTemplate namedParameterJdbcTemplate ;
	  /**分页构造函数
	   * @param sql 根据传入的sql语句得到一些基本分页信息
	   * @param currentPage 当前页
	   * @param pageSize 每页显示记录数
	   * @param namedParameterJdbcTemplate namedParameterJdbcTemplate实例
	   */
	  public Page(String sql,int currentPage,int pageSize,NamedParameterJdbcTemplate namedParameterJdbcTemplate,Map<String,Object> paramMap){
		  sql=sql.replaceAll(DOUBLE_REGEXP, "");
	    if(namedParameterJdbcTemplate == null){

	      throw new IllegalArgumentException("com.rykj.qxj.util.Page.namedParameterJdbcTemplate is null,please initial it first. ");
	    }else if(sql == null || sql.equals("")){
	      throw new IllegalArgumentException("com.rykj.qxj.util.Page.sql is empty,please initial it first. ");
	    }
	    //设置每页显示记录数
	    setPageSize(pageSize);
	    //设置要显示的页数
	    setCurrentPage(currentPage);
	    //转化为小写并去除所有空格
	    String replaceSql = sql.toLowerCase().replace(" ", "");
	    int lastIndexOf = replaceSql.lastIndexOf("groupby");
	    String totalSQL="";
	    if(lastIndexOf==-1) {
	    	 /*String[] strs = sql.toLowerCase().split("from");
			  strs[0] = "select count(*) from ";
			   totalSQL = StringUtils.join(strs,"");*/
	    	//String[] strs = sql.split("from|FROM");
	    	//忽略from大小写的正则表达式
	    	String[] strs = sql.split("(?i)from");
			strs[0] = "select count(*)  ";
			totalSQL = StringUtils.join(strs,"from");
	    }else {
	    	 //计算总记录数
		    StringBuffer total = new StringBuffer(" SELECT count(*) FROM ( ");
		    total.append(sql);
		    total.append(" ) totalTable ");
		    totalSQL=total.toString();
	    	
	    }
	    //给NamedParameterJdbcTemplate赋值
	    setNamedParameterJdbcTemplate(namedParameterJdbcTemplate);
	    logger.debug("执行查询之前的的sql语句:"+sql);
	    logger.debug("开始查询满足条件的总记录数据=======");
	    //总记录数
	    setTotalRows(getNamedParameterJdbcTemplate().queryForObject(totalSQL, paramMap, Integer.class));
	    //计算总页数
	    setTotalPages();
	    //计算起始行数
	    setStartIndex();
	    //计算结束行数
	    setLastIndex();
	    //装入结果集
	    logger.debug("开始查询满足条件的列表数据=======");
	    List<Map<String, Object>> resultList=new ArrayList<Map<String,Object>>();
	    List<Map<String, Object>> queryForList = namedParameterJdbcTemplate.queryForList(getMySQLPageSQL(sql,startIndex,pageSize), paramMap);
	    if(CollectionUtils.isNotEmpty(queryForList)) {
	    	 setresult(queryForList);
	    }else {
	    	 setresult(resultList);
	    }
	    if(paramMap==null||paramMap.size()==0) {
	    	 logger.info("此查询为无条件查询!");
	    }else {
	    String requestParam = SignUtil.convertMapToJson(paramMap);
	    logger.info("请求参数:"+requestParam);
	    }
	  }
	    /**
		 * 构造MySQL数据分页SQL 
		 * @param queryString
		 * @param startIndex
		 * @param pageSize
		 * @return
		 */
		public String getMySQLPageSQL(String queryString, Integer startIndex, Integer pageSize)
		{
			String result = "";
			if (null != startIndex && null != pageSize)
			{
				result = queryString + " limit " + startIndex + "," + pageSize;
			} else if (null != startIndex && null == pageSize)
			{
				result = queryString + " limit " + startIndex;
			} else
			{
				result = queryString;
			}
			return result;
		}
	  public int getCurrentPage() {
	    return currentPage;
	  } 
 
	  public void setCurrentPage(int currentPage) {
	    this.currentPage = currentPage;
	  }
 
	  public int getPageSize() {
		return pageSize;
	  }
	  public void setPageSize(int pageSize) {
			this.pageSize = pageSize;
	  }
	  public List getresult() {
	    return result;
	  }
 
	  public void setresult(List result) {
	    this.result = result;
	  }
 
	  public int getTotalPages() {
	    return totalPages;
	  }
	 //计算总页数
	  public void setTotalPages() {
	    if(totalRows % pageSize == 0){
	      this.totalPages = totalRows / pageSize;
	    }else{
	      this.totalPages = (totalRows / pageSize) + 1;
	    }
	  }
 
	  public int getTotalRows() {
	    return totalRows;
	  }
 
	  public void setTotalRows(int totalRows) {
	    this.totalRows = totalRows;
	  }
 
	  public int getStartIndex() {
	    return startIndex;
	  }
 
	  public void setStartIndex() {
	    this.startIndex = (currentPage - 1) * pageSize;
	  }
 
	  public int getLastIndex() {
	    return lastIndex;
	  }
 
	 
	   
	 public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
		return namedParameterJdbcTemplate;
	}

	public void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
		this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
	}
	//计算结束时候的索引
	  public void setLastIndex() {
		logger.info("查询结果当前页数:"+currentPage);
		logger.info("每一页显示的记录数:"+pageSize);
	    logger.info("满足条件的总记录数:"+totalRows);
	    if( totalRows < pageSize){
	      this.lastIndex = totalRows;
	    }else if((totalRows % pageSize == 0) || (totalRows % pageSize != 0 && currentPage < totalPages)){
	      this.lastIndex = currentPage * pageSize;
	    }else if(totalRows % pageSize != 0 && currentPage == totalPages){//最后一页
	      this.lastIndex = totalRows ;
	    }
	  }
	  
	  @Override
	public String toString() {
		return "Page [pageSize=" + pageSize + ", totalRows=" + totalRows + ", totalPages=" + totalPages
				+ ", currentPage=" + currentPage + ", startIndex=" + startIndex + ", lastIndex=" + lastIndex
				+ ", result=" + result + "]";
	}
}


